package com.chen.cloudpicture.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chen.cloudpicture.common.ResultUtils;
import com.chen.cloudpicture.config.CosClientConfig;
import com.chen.cloudpicture.exception.BusinessException;
import com.chen.cloudpicture.exception.ErrorCode;
import com.chen.cloudpicture.exception.ThrowUtils;
import com.chen.cloudpicture.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * 通用文件上传服务，继续封装CosManager
 * @deprecated 表示已废弃，改为使用 upload 包的模板模式优化
 */
@Slf4j
@Service
@Deprecated
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile    上传的文件
     * @param uploadPathPrefix 上传的路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(multipartFile);
        // 2.生成图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        // 拼接文件上传地址，当前日期加随机数加原文件后缀,format格式化,%s占位符
        // 原文件名可能重复，有些特殊文件名可能还由特殊字符影响上传
        String uploadFileName = String.format("%s_%s.%s", uploadPathPrefix, uuid, fileSuffix);
        // 最终上传地址
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        // 3.解析结果并返回
        // 与FileController的测试上传接口编写基本一样
        File file = null;
        // 上传文件
        try {
            // 生成临时文件，第一个参数是文件前缀，第二个参数是文件后缀，默认是.tmp
            file = File.createTempFile(uploadFilePath, null);
            // 将文件内容写入临时文件
            multipartFile.transferTo(file);
            // 对象存储，获得上传结果对象，解析信息
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 校验文件
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过2MB");
        // 校验文件格式(后缀)
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀列表
        final List<String> validSuffixList = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp", "svg");
        ThrowUtils.throwIf(!validSuffixList.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
    }

    /**
     * // 清理临时文件
     */
    private static void deleteTempFile(File file) {
        if (file != null) {
            boolean delete = file.delete();
            if (!delete) {
                log.warn("file delete err, filepath = {}", file.getAbsoluteFile());
            }
        }
    }

    /**
     * URL上传图片
     */
    public UploadPictureResult uploadPicture(String fileUrl, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(fileUrl);
        // 2.生成图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = FileUtil.mainName(fileUrl);
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        // 拼接文件上传地址，当前日期加随机数加原文件后缀,format格式化,%s占位符
        // 原文件名可能重复，有些特殊文件名可能还由特殊字符影响上传
        String uploadFileName = String.format("%s_%s.%s", uploadPathPrefix, uuid, fileSuffix);
        // 最终上传地址
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        // 3.解析结果并返回
        // 与FileController的测试上传接口编写基本一样
        File file = null;
        // 上传文件
        try {
            // 生成临时文件，第一个参数是文件前缀，第二个参数是文件后缀，默认是.tmp
            file = File.createTempFile(uploadFilePath, null);
            // 下载文件元信息到临时文件
            HttpUtil.downloadFile(fileUrl, file);
            // 对象存储，获得上传结果对象，解析信息
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 根据URL创建文件
     * 通过HTTP的HEAD请求返回文件的元信息（文件大小、文件类型等）
     * HEAD请求只返回HTTP的响应头信息，而不会下载文件的内容，所以比GET等请求更高效，降低网络流量的消耗
     */
    private void validPicture(String fileUrl) {
        // 1.校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址为空");

        // 2.校验 URL 格式
        try {
            // 利用URL类来校验格式，能新建就代表格式正确
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
        }

        // 3.校验 URL 协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 4.发送 HEAD 请求验证文件是否存在
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 不能正确返回可能是图床不支持HEAD请求，不能代表文件有问题，所以直接返回
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK)
                return;

            // 5.文件存在，文件类型校验
            String contentType = httpResponse.header("Content-Type");
            // 不为空才校验，这样校验规则相对宽松
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }

            // 6.文件存在，文件大小的校验
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }

        } finally {
            if (httpResponse != null)
                httpResponse.close();
        }
    }
}
